import React, {Component} from 'react';
import {withRouter,Link, Switch, Route} from 'react-router-dom'
import { LocaleProvider } from 'antd';
import zh_CN from 'antd/lib/locale-provider/zh_CN';
import 'moment/locale/zh-cn';
import $ from 'jquery'
import u from '../../common.js'
import Loading from "./../loading"//加载中样式
import { Layout, Menu,  Icon ,Button, Form, Pagination, Modal,Input,Radio,Table,message} from 'antd';
import Keywords2 from './system-words2.jsx'//智能模式
import '../../static/icon/iconfont.css'



import "../../static/systemSetup/system-base.styl"

const { SubMenu } = Menu;
const { Header, Content, Sider } = Layout;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const {TextArea} = Input;




export default class SystemKeywords extends React.Component{
  constructor(props){
    super(props);
       //表格配置项
       this.state = {
        selectedRowKeys: [],//选中项
        selectedRows:[],//选中项的值
        visible: false,
        visible2: false,
        visible3: false,
        visible4: false,
        visible5:false,//高级模式弹窗
        flag:false,
        valueArr:['情报','案件','舆情'],//类型
        key_group_name:[],//关键词名
        emptyIds:[],//所有的id
        key_group:[],//表达式
        add_time:"2018-09-11 17:50:00",//添加时间
        key_type:1,
        number:0,//关键词数量
        value:0,//类型type
        // ID:i,
        dataArr:[],//关键词数组
        current: 1,  //当前页数
      size: 10,    //每页显示条数
      total: 0,   //总条数
      pagesize: 0, //
      text:'暂无任何数据',
      singleID:null,//要删除的单个ID
      editRowKey:{},//要修改的关键词
    }
  }
 
    //渲染前调用
    componentWillMount(){
      
    }
   //获取选中的行以及选中行的值
      onSelectChange =(selectedRowKeys, selectedRows) => {
        this.setState({ 
          selectedRowKeys:selectedRowKeys,
          selectedRows:selectedRows,
        });
        console.log(selectedRows)

      }
    //弹出框
    addKeywords = () => {
        this.setState({
          visible: true,
        });
      }
      //高级模式弹窗
      seniorKeywords=()=>{
        // this.setState({
        //   visible5: true,
        // });
        window.location.href=u.testurl+'/systemBase/Keywords2'
      }
    delKeywords =(id)=>{
      // if(this.state.selectedRowKeys.length<1){
      //   message.warning('请先选择要删除的项')
      //   return
      // }else{
      //   this.setState({
      //     visible2: true,
      //   });
      // }
          this.setState({
          visible2: true,
          singleID:id,
        },()=>{
          console.log(this.state.singleID)
        });
    }  
    editKeywords =(val)=>{
      // if(this.state.selectedRowKeys.length<1){
      //   message.warning('请先选择要修改的项')
      //   return
      // }else{
      //   this.setState({
      //     visible3: true,
      //   });
      // }
     console.log(val)
     this.setState({
      visible3: true,
      editRowKey:val,
    });
    } 
   
    //点击确定 添加关键词
    handleOk = (e) => {
      
      let keyNameVal=$.trim($('.keyName').val())
      let inputVal=$.trim($('.input-area').val())
     //非空验证
      if(keyNameVal.length < 1){
        message.error('请先输入关键词');
        return
      }else if(inputVal.length < 1){
        message.error('请先输入关键词表达式');
        return
      }
        
       let keyArr=
       {
        key_group_name:keyNameVal,
        key_group:inputVal,
        add_time:u.unixTime(),
        key_type:this.state.value
        
      }
        u.insertKey(keyArr,data =>{
          console.log(data)
          console.log(keyArr)
          let arr = this.state.dataArr.slice(0)
          
          let key = {
                ID: arr.length+1,
                keyname: keyNameVal,
                keygroups:inputVal,
                types: this.state.valueArr[this.state.value],
              }
              // this.state.dataArr.forEach(item=>{
              //     this.state.key_group_name.push(item.key_group_name)
              // })
             
              //重复验证
              if($.inArray(keyNameVal,this.state.key_group_name) >= 0){
                message.error('关键词重复');
                return
              }else{
                // arr.push(key);
                this.setState({
                  visible: false,//添加关键词弹框显示
                  visible2: false,//删除关键词显示
                  visible3: false,//修改关键词显示
                 
                });
                // window.location.reload();

                if(this.state.value==0){
                  // this.qingbao()
                  $('.qing').trigger('click')
                }else if(this.state.value==1){
                  $('.anJian').trigger('click')
                }else if(this.state.value==2){
                  $('.yuQing').trigger('click')
                }
                // this.showKeywords()
              }
             
          
         })
         //将表单框中的值置空
         setTimeout(()=>{
          $('.keyName').val('')
          $('.input-area').val('')
         },2000)
      }
      //点击确定  添加高级模式关键词
     seniorOK=()=>{
       console.log('高级模式关键词')
       this.setState({
         visible5:false,
       })
     }
      //删除关键词 
      delKey =(e) =>{
        console.log('关闭删除关键词')
        let delArr= this.state.selectedRows;
       let ids=[];//要删除的黑名单的id
       for(var i=0;i<delArr.length;i++){
        //  ids.push(delArr[i].id?delArr[i].id:delArr[i].ID)
        ids.push(delArr[i].id)
       }
       console.log(ids.toString())
        u.delKeygroup({
          ids: ids.length > 0 ? ids.toString() : this.state.singleID.toString(),
        },data=>{
          console.log(data)
          this.setState({
             visible: false,
            visible2: false,
            visible3: false,
            selectedRowKeys:[],
            selectedRows:[]
          })

          // window.location.reload();
          // this.showKeywords()
          if(this.state.value==0){
            // this.qingbao()
            $('.qing').trigger('click')
          }else if(this.state.value==1){
            $('.anJian').trigger('click')
          }else if(this.state.value==2){
            $('.yuQing').trigger('click')
          }
        }
        )
        
      }
      //修改关键词  打开复制的添加关键词
      editKey =(e) =>{
       
        this.setState({
          visible: false,
          visible2: false,
          visible3: false,
          visible4:true,//复制层打开
        });
        setTimeout(()=>{
          let keyName=this.state.editRowKey.key_group_name
          let keyGroup=this.state.editRowKey.key_group
          let keyType=this.state.editRowKey.key_type
          document.getElementById("keyName2").value=keyName
          document.getElementById("input-area2").value=keyGroup
          this.setState({
            value:keyType
          })
        },1000);
        
     
      }

      //点击确定 修改关键词
      editThiskey=()=>{
       
        //修改关键词接口 
        u.editKey({
          // key_group_name:this.state.selectedRows[0].key_group_name,
          // key_group:this.state.selectedRows[0].key_group,
          // modify_time:u.unixTime(),
          // id:this.state.selectedRows[0].id,
          // key_type:this.state.selectedRows[0].key_type,
          key_group_name:$('#keyName2').val(),
          key_group:$('#input-area2').val(),
          modify_time:u.unixTime(),
          id:this.state.editRowKey.id,
          key_type:this.state.value,
        },data =>{
          console.log(data)
         let key=this.state.editRowKey.ID - 1;
         console.log(key)
         let arr=this.state.dataArr.slice(0)
         arr[key].keyname=document.getElementById("keyName2").value
         arr[key].keygroups=document.getElementById("input-area2").value
         arr[key].types=this.state.valueArr[this.state.value]
           this.setState({
             dataArr:arr
           })
          console.log(this.state.dataArr)
          this.setState({
            visible4:false,
          })
        }
        )
        
      }
      //点击全部显示关键词
      quanbu =(e)=>{
        $( e.target).addClass('blue').siblings().removeClass('blue')
         //查询关键词接口
         u.queryKey({
          key_type:'',
          page:1,
          size:500,
         },data =>{
          if (data.data.length==0) return
        data.data.forEach(item => {
         //  let index=data.data.IndexOf(item);
          item.ID=data.data.indexOf(item)+1,//bug1
          item.keyname=item.key_group_name,
          item.keygroups=item.key_group,
          item.types=this.state.valueArr[item.key_type]
        });
        this.setState((prevState)=>({
          dataArr:data.data
        }))
      
      })
      }
      //点击情报显示关键词
      qingbao =(e)=>{
       $( e.target).addClass('blue').siblings().removeClass('blue')
             //查询关键词接口
             u.queryKey({
               key_type:0,
              //  page:1,
              //  size:500,
              },data =>{
                if (data.data.length==0){
                    this.setState((prevState)=>({
                      dataArr:''
                    }))
                }else{
                  data.data.forEach(item => {
                    //  let index=data.data.IndexOf(item);
                     item.ID=data.data.indexOf(item)+1,//bug1
                     item.keyname=item.key_group_name,
                     item.keygroups=item.key_group,
                     item.types=this.state.valueArr[item.key_type]
                   });
                   this.setState((prevState)=>({
                     dataArr:data.data
                   }))
                }
           })
      }
      //点击案件显示关键词
      anjian =(e)=>{
        $( e.target).addClass('blue').siblings().removeClass('blue')
        //查询关键词接口
        u.queryKey({
          key_type:1,
          // page:1,
          // size:500,
        },data =>{
          console.log(data)
          if (data.data.length==0){
            this.setState((prevState)=>({
              dataArr:''
            }))
          }else{
            data.data.forEach(item => {
              item.ID=data.data.indexOf(item)+1,//bug1
              item.keyname=item.key_group_name,
              item.keygroups=item.key_group,
              item.types=this.state.valueArr[item.key_type]
            });
            this.setState((prevState)=>({
              dataArr:data.data
            }))
          }
     
      
      })
 }
     //舆情案件显示关键词
     yuqing =(e)=>{
      $( e.target).addClass('blue').siblings().removeClass('blue')
      //查询关键词接口
      u.queryKey({
        key_type:2,
        // page:1,
        // size:500,
      },data =>{
        if (data.data.length==0){
          this.setState((prevState)=>({
            dataArr:''
          }))
        }else{
          data.data.forEach(item => {
            item.ID=data.data.indexOf(item)+1,//bug1 表格索引
            item.keyname=item.key_group_name,
            item.keygroups=item.key_group,
            item.types=this.state.valueArr[item.key_type]
          });
          this.setState((prevState)=>({
            dataArr:data.data
          }))
        }
    
    
    })
}
     //清空关键词 清除选中状态
     emptyArr=(e)=>{
       this.setState({
         selectedRowKeys:[],
         selectedRows:[],
       })
      
     }
      //点击取消
      handleCancel = (e) => {
        this.setState({
          visible: false,
          visible2: false,
          visible3: false,
          visible4:false,
          visible5:false,
        });
      }    
      //单选框
      onChange = (e) => {
        
        this.setState({
          value: e.target.value,
        });
      }
      itemRender=(current, type, originalElement)=> {
        if (type === 'prev') {
          return <a>上一页</a>;
        } if (type === 'next') {
          return <a>下一页</a>;
        }
        return originalElement;
      }

      changePage(page,pageSize){

      }
      //封装渲染函数
      showKeywords=()=>{
        u.queryKey({
          key_type:'',
          // page:Math.ceil(this.state.dataArr.length/10)||1,
          // size:10,
        },data =>{
          console.log(data)
       if (data.data.length==0) return
        data.data.forEach(item => {
          item.ID=data.data.indexOf(item)+1,//bug1
          item.keyname=item.key_group_name,
          item.keygroups=item.key_group,
          item.types=this.state.valueArr[item.key_type]
        });
       
        this.setState((prevState)=>({
          dataArr:data.data
        }))//渲染出来的所有关键词数组

      })
      }
      //第一次渲染后的函数
      componentDidMount(){
        $('.default').trigger("focus")
        //全部关键词
        //查询关键词接口
       this.showKeywords()
      }

      onDownLoad() {
        window.open(u.baseUrl + '/help/help.docx')
      }
    render(){
        const state = this.state;
       
          const {  selectedRowKeys } = this.state;
          const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
          };
          const hasSelected = selectedRowKeys.length > 0;
          //表格
        const columns = [{
          title: 'ID',
          dataIndex: 'ID',
          key: 'ID',
          width: 70,
          pagination:false,
        
        }, {
          title: '关键词组',
          dataIndex: 'keyname',
          key: 'keyname',
          width: 200,
        }, {
          title: '关键词表达式',
          dataIndex: 'keygroups',
          key: 'keygroups',
          width: 350,
        }, {
          title: '类型',
          dataIndex: 'types',
          key: 'types',
          width: 120,
        },
        {
          title: '操作',
          key: 'action',
          width: 200,
          render: (text, record) => (
            <span style={{whiteSpace:"nowrap",display:"flex",justifyContent:"space-between",width:"50%",marginLeft:"25%"}}>
             
              <a href="javascript:;" className="modify" onClick={()=>{this.editKeywords(record)}} >
               <img src={require("../../static/image/icon-edit.png")} alt=""/>
              修改
              </a>
              <a href="javascript:;" className="del" onClick={()=>{this.delKeywords(record.id)}}>
              {/* <img src={require("../../static/image/icon-del.png")} alt=""/> */}
              <i className="iconfont icon-territory_del"></i>
              删除</a>
            
              

            </span>
          ),
        }];
 
        return(
            <div className="container">
             <Loading className="loadingPage"/>
               <Layout>
                    <Layout>
                        <Content style={{ background: '#fff', margin: 0, minHeight: 280 , overflowY:"hidden"}}>
                          <div className="btns">
                            <p>类型：</p>
                            <span className='blue' onClick={this.quanbu}>全部</span>
                            <span className='qing' onClick={this.qingbao}>情报</span>
                            <span className='anJian' onClick={this.anjian}>案件</span>
                            <span className='yuQing' onClick={this.yuqing}>舆情</span>
                          </div>
                          <div className="btns-center">
                            <span style={{color:"#9ba2ab"}}>共搜索到&nbsp;<i>{this.state.dataArr.length}</i>&nbsp;条数据</span>
                            <div className="tips">
                              <Icon type="info-circle" />
                              <span style={{color:"#9ba2ab"}}>已选择 {this.state.selectedRowKeys.length} 项 </span>
                              <a href="javsscript:;" onClick={this.emptyArr}>清空</a>
                            </div>
                            <div className="options">
                                {/* <Button type="primary">导出</Button> */}
                                <Button className="btnBorder" onClick={this.delKeywords}>删除</Button>
                                <Button  onClick={this.addKeywords} className="btnBorder">添加</Button>
                                <Button className="btnBorder" onClick={this.seniorKeywords}>智能模式</Button>
                                {/* 添加关键词 */}
                                <Modal       
                                    className='addStyle'        
                                    title={<span>
                                    <span className='addStyleFont'>添加关键词</span></span>}
                                    visible={this.state.visible}
                                    // onOk={this.handleOk}
                                    onCancel={this.handleCancel}
                                    footer={[
                                      <Button  onClick={this.handleCancel}>
                                        取消
                                      </Button>,
                                      <Button onClick={this.handleOk} type="primary">
                                        确定
                                      </Button>,
                                    ]}
                                    >
                                    <div className="addRow">
                                       <div className="label">
                                        <span style={{whiteSpace:"nowrap"}} >关键词词组名称:</span>
                                       </div>
                                       <Input placeholder="请输入词组名称" style={{width:"60%"}} size="default" className="keyName" />
                                    </div>
                                    <div className="tishi2">该名称是关键词组的标识，不用于查询，可任意填写</div>
                                    <div className="addRow">
                                       <div className="label">
                                          <span>关键词表达式:</span>
                                       </div>   
                                       <TextArea className="input-area" placeholder="请输入关键词表达式" style={{width:"60%",height:"100px",resize:"none"}}/>
                                    </div>
                                    <div className="tishi2">高级模式下关键词表达式可以根据需求自行书写，具体配置方法请下载下方的关键词配置说明</div>
                                    <div className='download' onClick={this.onDownLoad.bind(this)}>配置文档下载 <Icon type="download" /></div>
                                    <div className="addRow">
                                       <div className="label">
                                          <span>关键词类型：</span>
                                        </div>  
                                        <RadioGroup onChange={this.onChange} value={this.state.value}>
                                            <Radio value={0} name="type">情报</Radio>
                                            <Radio value={1} name="type">案件</Radio>
                                            <Radio value={2} name="type">舆情</Radio>
                                        </RadioGroup>
                                    </div>
                                </Modal>
                                 {/* 复制的添加关键词 修改关键词*/}
                                 <Modal           
                                    className='addStyle'                  
                                    title={<span>
                                    <span className='addStyleFont'>添加关键词</span></span>}
                                    visible={this.state.visible4}
                                    // onOk={this.handleOk}
                                    onCancel={this.handleCancel}
                                    footer={[
                                      <Button  onClick={this.handleCancel}>
                                        取消
                                      </Button>,
                                      <Button onClick={this.editThiskey} type="primary">
                                        确定
                                      </Button>,
                                    ]}
                                    >
                                    <div className="addRow2">
                                       <div className="label">
                                        <span style={{whiteSpace:"nowrap"}} >关键词词组名称:</span>
                                       </div>
                                       <Input placeholder="请输入词组名称" style={{width:"60%"}} size="default" id="keyName2" />
                                    </div>
                                    <div className="addRow2">
                                       <div className="label">
                                          <span>关键词表达式:</span>
                                       </div>   
                                       <TextArea id="input-area2"  placeholder="请输入关键词表达式" style={{width:"60%",height:"100px",resize:"none"}}/>
                                    </div>
                                    <div className="addRow2">
                                       <div className="label">
                                          <span>关键词类型：</span>
                                        </div>  
                                        <RadioGroup onChange={this.onChange} value={this.state.value}>
                                            <Radio value={0} name="type" className='radioQ'>情报</Radio>
                                            <Radio value={1} name="type">案件</Radio>
                                            <Radio value={2} name="type" className='radioY'>舆情</Radio>
                                        </RadioGroup>
                                    </div>
                                </Modal>
                                {/* 删除关键词 */}
                                <Modal
                                  className='delStyle'
                                  title={<span> 
                                  <span className='delStyleFont'>删除</span></span>}
                                  visible={this.state.visible2}
                                  //  onOk={this.handleOk}
                                   onCancel={this.handleCancel}
                                   centered='true'
                                  footer={[
                                    <Button  onClick={this.handleCancel}>
                                      取消
                                    </Button>,
                                    <Button onClick={this.delKey} type="primary">
                                      确定
                                    </Button>,
                                  ]}
                                >
                                   <p style={{marginLeft:"10%",marginBottom:"10%"}}>是否删除该关键词？</p>
                                </Modal>
                                {/* 修改关键词 */}
                                <Modal
                                className='minModel'
                                  title={<span>
                                  <span>修改</span></span>}
                                  visible={this.state.visible3}
                                  //  onOk={this.handleOk}
                                   onCancel={this.handleCancel}
                                   centered={true}
                                  footer={[
                                    <Button  onClick={this.handleCancel}>
                                      取消
                                    </Button>,
                                    <Button onClick={this.editKey} type="primary">
                                      确定
                                    </Button>,
                                  ]}
                                >
                                   <p style={{marginLeft:"10%",marginBottom:"10%"}}>是否修改该关键词？</p>
                                </Modal>
                            </div>
                            {/* 表格 */}
                            
                             <Table {...this.state}  columns={columns} dataSource={this.state.dataArr} rowSelection={rowSelection} pagination={true}
                            style={{marginBottom:"2%"}} id='loadTable' locale={{emptyText:this.state.text}} total='12'
                            /> 
                          </div>
                         
                        </Content>
                    </Layout>
                    </Layout>
                
             </div>
         
        );
    }
}